class SendToFriendsController < ApplicationController

  FRIEND_COUNT = 3

  # GET /send_to_friends
  # shows the stf friend form
  def index
    @form_valid = true # don't show errors on unsubmitted form
    # init senderr
    @sender = Sender.new
    @sender.name  = "Your name"
    @sender.email = "sender@example.com"
    # init recipients    
    @recipients  = Array.new(FRIEND_COUNT) { |i| Recipient.new }
  end
  
  # POST /send_to_friends
  # POST /send_to_friends.xml
  def create
    @sender = Sender.new params[:sender]
    @recipients  = Array.new(FRIEND_COUNT) { |i| Recipient.new params["recipient_#{i}"] }
    
    @valid_recipients   = []
    @invalid_recipients = []
    @empty_recipients   = []
    
    @recipients.each do |r|
      if r.empty?
        @empty_recipients   << r
      elsif r.valid?
        @valid_recipients   << r
      else
        @invalid_recipients << r
      end
    end
    
    # the form is only valid if the sender if valid 
    # and at least one valid friend was received
    # and no invalid friends were received
    if @sender.valid? && @valid_recipients.size >= 1 && @invalid_recipients.empty?
      @form_valid = true
      # send out emails one-by-one
      @valid_recipients.each {|r| FriendMailer.deliver_message(@sender, r) }
    else
      @form_valid = false
      @all_friends_empty = @empty_recipients.size == FRIEND_COUNT
    end
  
    respond_to do |format|
      if @form_valid
        format.xml { render :xml => '<response success="0" />' }
        format.html # create.rhtml
      else
        format.xml  { render :action => 'errors' }
        format.html { render :action => 'index' }
      end
    end
    
  end
end
